﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp3
{
    class Program
    {
        private static Object objA = new Object();
        private static Object objB = new Object();
        public static void LockA()
        {
            if (Monitor.TryEnter(objA, 1000))
            {
                Thread.Sleep(1000);
                if (Monitor.TryEnter(objB, 2000))
                {
                    Monitor.Exit(objB);
                }
                else
                {

                    Console.WriteLine("LockB timeout");
                }
                Monitor.Exit(objA);
            }
            Console.WriteLine("LockA");
        }
        public static void LockB()
        {
            if (Monitor.TryEnter(objB, 2000))
            {
                Thread.Sleep(2000);
                if (Monitor.TryEnter(objA, 1000))
                {
                    Monitor.Exit(objA);
                }
                else
                {
                    Console.WriteLine("LockA timeout");
                }
                Monitor.Exit(objB);
            }
            Console.WriteLine("LockB");
        }
        public static void Main()
        {
            Thread threadA = new Thread(LockA);
            Thread threadB = new Thread(LockB);
            threadA.Start();
            threadB.Start();
            Thread.Sleep(4000);
            Console.WriteLine("线程结束");

            Console.ReadKey();
        }
    }
}
